# coding:utf-8
import os

from flask import g, request

from app.app import Flask
from .libs.Logger import MyLogger, thread_local
from .libs.init import mongo, celery, socket_io, scheduler
from .models.base import db
from . import models
from gevent import pywsgi
from flask_migrate import Migrate
import logging
from logging.handlers import RotatingFileHandler
import threading
import time
import uuid


def register_blueprint_api(app):
    from app.api.v1 import create_blueprint_v1
    app.register_blueprint(create_blueprint_v1(), url_prefix='/api')


def register_before_request(app):
    @app.before_request
    def before_request():
        g.request_start_time = time.time()
        app.thread_local.logid = g.lod_id = uuid.uuid1().time
        app.logger.debug(f'request:{request.data}')


def register_after_request(app):
    @app.after_request
    def after_request(response):
        now = time.time()
        app.logger.debug(f'耗时:{now - g.request_start_time}')
        response.headers['X-Log-Id'] = g.lod_id
        return response


def create_app():
    app = Flask(__name__)
    setting_path = os.path.abspath('./app/config/setting.py')
    if os.path.isfile(setting_path):
        app.config.from_object("app.config.setting")
        app.config.from_object("app.config.secure")
    else:
        app.config.from_object("app.config.setting_prod")
        app.config.from_object("app.config.secure_prod")

    register_blueprint_api(app)
    # socket_io.init_app(app, cors_allowed_origins='*')
    mongo.init_app(app)
    celery.init_app(app)
    migrate = Migrate(app, db)
    register_before_request(app)
    register_after_request(app)
    # 启动scheduler
    scheduler.init_app(app)
    scheduler.start()
    db.init_app(app)
    with app.app_context():
        db.create_all()
        MyLogger('myapp', level=logging.WARNING, console=False, file=True, filename='logs/flask.log')
    app.thread_local = thread_local
    return app
